#!/usr/bin/env python3
"""
Redis配置助手
帮助快速配置Redis连接参数
"""

import os
import re

def update_env_file():
    """更新.env文件中的Redis配置"""
    env_file = '.env'
    
    if not os.path.exists(env_file):
        print("❌ .env文件不存在，请先创建.env文件")
        return False
    
    print("🔧 Redis配置助手")
    print("=" * 50)
    
    # 获取用户输入
    print("请输入Redis连接信息:")
    host = input("Redis主机地址 [192.168.1.25]: ").strip() or "192.168.1.25"
    port = input("Redis端口 [6379]: ").strip() or "6379"
    password = input("Redis密码 (如果没有密码请直接回车): ").strip()
    db = input("Redis数据库编号 [0]: ").strip() or "0"
    
    # 构建Redis URL
    if password:
        redis_url = f"redis://:{password}@{host}:{port}/{db}"
        print(f"\n✅ 将使用带密码的Redis连接")
    else:
        redis_url = f"redis://{host}:{port}/{db}"
        print(f"\n✅ 将使用无密码的Redis连接")
    
    print(f"📍 Redis URL: {redis_url}")
    
    # 确认更新
    confirm = input("\n是否更新.env文件? (y/N): ").strip().lower()
    if confirm not in ['y', 'yes']:
        print("❌ 取消更新")
        return False
    
    try:
        # 读取现有.env文件
        with open(env_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 更新Redis配置
        # 替换REDIS_URL
        redis_url_pattern = r'REDIS_URL=.*'
        if re.search(redis_url_pattern, content):
            content = re.sub(redis_url_pattern, f'REDIS_URL={redis_url}', content)
        else:
            content += f'\nREDIS_URL={redis_url}\n'
        
        # 更新其他Redis配置
        redis_configs = {
            'REDIS_HOST': host,
            'REDIS_PORT': port,
            'REDIS_PASSWORD': password,
            'REDIS_DB': db
        }
        
        for key, value in redis_configs.items():
            pattern = rf'{key}=.*'
            replacement = f'{key}={value}' if value else f'# {key}='
            
            if re.search(pattern, content):
                content = re.sub(pattern, replacement, content)
            elif value:  # 只有当值不为空时才添加
                content += f'{key}={value}\n'
        
        # 写回文件
        with open(env_file, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print("✅ .env文件更新成功!")
        print("\n🔄 请重启应用以使配置生效:")
        print("1. 停止当前服务器 (Ctrl+C)")
        print("2. 运行: python app.py")
        print("\n🧪 测试连接:")
        print("python test_redis_connection.py")
        
        return True
        
    except Exception as e:
        print(f"❌ 更新.env文件失败: {str(e)}")
        return False

def show_current_config():
    """显示当前Redis配置"""
    try:
        from config import Config
        print("📋 当前Redis配置:")
        print(f"  URL: {Config.REDIS_URL}")
        print(f"  Host: {Config.REDIS_HOST}")
        print(f"  Port: {Config.REDIS_PORT}")
        print(f"  Password: {'***设置***' if Config.REDIS_PASSWORD else '未设置'}")
        print(f"  DB: {Config.REDIS_DB}")
    except Exception as e:
        print(f"❌ 无法读取当前配置: {str(e)}")

if __name__ == "__main__":
    print("🔐 Redis配置助手")
    print("=" * 50)
    
    # 显示当前配置
    show_current_config()
    print()
    
    # 询问是否要更新配置
    action = input("是否要更新Redis配置? (y/N): ").strip().lower()
    if action in ['y', 'yes']:
        success = update_env_file()
        if success:
            print("\n🎉 配置完成!")
        else:
            print("\n❌ 配置失败，请手动编辑.env文件")
    else:
        print("👋 如需配置，请重新运行此脚本")
        print("\n💡 手动配置说明:")
        print("1. 编辑.env文件")
        print("2. 设置REDIS_URL=redis://:password@host:port/db")
        print("3. 重启应用")